from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import GepParameter
from app.utils.decorators import admin_required

gep_parameters_bp = Blueprint('gep_parameters', __name__)

@gep_parameters_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_gep_parameters():
    """获取GEP参数列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取搜索参数
    gep_year = request.args.get('gepYear', '')
    gep_city = request.args.get('gepCity', '')
    gep_district = request.args.get('gepDistrict', '')
    gep_town = request.args.get('gepTown', '')
    
    query = GepParameter.query
    
    # 根据搜索条件过滤
    if gep_year:
        query = query.filter(GepParameter.year == gep_year)
    if gep_city:
        query = query.filter(GepParameter.gepCity.contains(gep_city))
    if gep_district:
        query = query.filter(GepParameter.gepDistrict.contains(gep_district))
    if gep_town:
        query = query.filter(GepParameter.gepTown.contains(gep_town))
    
    # 限制最多返回100条数据
    total_count = query.count()
    if total_count > 100:
        # 如果总数超过100，调整分页参数
        per_page = min(per_page, 100)
        page = min(page, (total_count + per_page - 1) // per_page)
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    parameters = pagination.items
    
    return jsonify({
        'gep_parameters': [param.to_dict() for param in parameters],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': min(pagination.total, 100),
            'pages': pagination.pages
        }
    }), 200

@gep_parameters_bp.route('/<int:param_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_gep_parameter(param_id):
    """获取单个GEP参数详情"""
    parameter = GepParameter.query.get(param_id)
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    return jsonify({
        'gep_parameter': parameter.to_dict()
    }), 200

@gep_parameters_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_gep_parameter():
    """创建GEP参数"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['year', 'gepCity', 'gepDistrict', 'gepTown']
    for field in required_fields:
        if not data.get(field):
            return jsonify({'message': f'字段 {field} 不能为空'}), 400
    
    # 检查唯一性约束
    existing = GepParameter.query.filter_by(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown']
    ).first()
    
    if existing:
        return jsonify({'message': '该地区该年份的参数已存在'}), 400
    
    # 创建新参数
    parameter = GepParameter(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown'],
        inAgricultural=data.get('inAgricultural'),
        inForestry=data.get('inForestry'),
        inAnimalHusbandry=data.get('inAnimalHusbandry'),
        inFishery=data.get('inFishery'),
        inEcologicalEnergy=data.get('inEcologicalEnergy'),
        inElectricityPrice=data.get('inElectricityPrice'),
        inWaterResources=data.get('inWaterResources'),
        inLocalWaterPrice=data.get('inLocalWaterPrice'),
        inProtectedArea=data.get('inProtectedArea'),
        inProtectedCost=data.get('inProtectedCost'),
        inNoiseReductionAmount=data.get('inNoiseReductionAmount'),
        inNoiseCost=data.get('inNoiseCost'),
        inTourismRevenue=data.get('inTourismRevenue'),
        inHousingAreaPerCapita=data.get('inHousingAreaPerCapita'),
        inHousePrice=data.get('inHousePrice'),
        inHotelRooms=data.get('inHotelRooms'),
        inRoomPrice=data.get('inRoomPrice'),
        inUrbanPopulation=data.get('inUrbanPopulation'),
        inOccupancyRate=data.get('inOccupancyRate'),
        inLeisureTime=data.get('inLeisureTime'),
        inAverageIncome=data.get('inAverageIncome'),
        creator=str(current_user_id)
    )
    
    try:
        db.session.add(parameter)
        db.session.commit()
        return jsonify({
            'message': '创建成功',
            'gep_parameter': parameter.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@gep_parameters_bp.route('/<int:param_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_gep_parameter(param_id):
    """更新GEP参数"""
    current_user_id = get_jwt_identity()
    parameter = GepParameter.query.get(param_id)
    
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    data = request.get_json()
    
    # 允许更新的字段
    allowed_fields = [
        'inAgricultural', 'inForestry', 'inAnimalHusbandry', 'inFishery',
        'inEcologicalEnergy', 'inElectricityPrice', 'inWaterResources',
        'inLocalWaterPrice', 'inProtectedArea', 'inProtectedCost',
        'inNoiseReductionAmount', 'inNoiseCost', 'inTourismRevenue',
        'inHousingAreaPerCapita', 'inHousePrice', 'inHotelRooms',
        'inRoomPrice', 'inUrbanPopulation', 'inOccupancyRate',
        'inLeisureTime', 'inAverageIncome'
    ]
    
    # 更新字段
    for field in allowed_fields:
        if field in data:
            setattr(parameter, field, data[field])
    
    parameter.updater = str(current_user_id)
    
    try:
        db.session.commit()
        return jsonify({
            'message': '更新成功',
            'gep_parameter': parameter.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

@gep_parameters_bp.route('/<int:param_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_gep_parameter(param_id):
    """删除GEP参数"""
    parameter = GepParameter.query.get(param_id)
    
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    try:
        db.session.delete(parameter)
        db.session.commit()
        return jsonify({'message': '删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除失败: {str(e)}'}), 500 